package com.api.doc.search.util;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.api.browser.bean.SearchConditionOption;
import com.api.browser.util.ConditionType;
import com.engine.doc.util.CheckPermission;
import com.engine.doc.util.TimeZoneUtil;
import com.engine.hrm.biz.HrmClassifiedProtectionBiz;

import weaver.docs.docs.DocManager;
import weaver.general.BaseBean;
import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.systeminfo.setting.HrmUserSettingComInfo;

/**
 * sqlwhere条件拼装
 *
 * @author wangqs
 */
public class DocListUtil {

  private String sqlWhere = " t1.id=t2.sourceid ";
  private boolean needRight = true;

  public DocListUtil(HttpServletRequest request, User user, DocTableType docTableType) {
    this.packageCondition(request, user, docTableType);
  }

  public DocListUtil(
      HttpServletRequest request, User user, DocTableType docTableType, boolean needRight) {
    if (!needRight || user == null) { // user为null，登录前门户元素more页面
      sqlWhere = "";
      this.needRight = false;
    }
    this.packageCondition(request, user, docTableType);
  }

  /** 封装查询条件 */
  private void packageCondition(HttpServletRequest request, User user, DocTableType docTableType) {

    String belongtoids = "";
    if (needRight) {
      HrmUserSettingComInfo userSetting = new HrmUserSettingComInfo();
      String belongtoshow = userSetting.getBelongtoshowByUserId(user.getUID() + "");
      belongtoids = user.getBelongtoids();
      if ("1".equals(belongtoshow) && "0".equals(user.getAccount_type()) && !"".equals(belongtoids))
        belongtoids += "," + user.getUID();
      else belongtoids = "";
    }

    Enumeration paramNames = request.getParameterNames();

    String docstatus = "";
    String customSql = "";
    if (docTableType == DocTableType.DOC_COPYMOVE) {
      sqlWhere = " t1.seccategory = " + request.getParameter("sourceId");
    }
    while (paramNames.hasMoreElements()) {
      String paramName = (String) paramNames.nextElement();
      String paramValue = Util.null2String(request.getParameter(paramName));

      boolean isCustom = true; // 是否是自定义字段

      for (DocCondition condition : DocCondition.values()) {
        if (paramValue.isEmpty()) continue;

        if (condition.getConditionType() == ConditionType.DATE) {
          if (paramName.equals(condition.getName() + ConditionUtil.DATE_SELECT)
              && !"6".equals(paramValue)) { // 只有6-时间范围，页面才传开始到结束时间，这里需要自己处理
            sqlWhere += packDateType(condition.getName(), paramValue, condition);
          } else if (paramName.equals(condition.getName() + ConditionUtil.DATE_FROM)) {
            //						if(paramValue.equals(request.getParameter(condition.getName() +
            // ConditionUtil.DATE_TO))){ //开始日期==结束日期
            //							paramValue = TimeZoneUtil.getServerDate1(paramValue,"begin");
            //							sqlWhere += " and " + condition.getName() + "='" +  paramValue + "'";
            //						}else{
            String time_paramValue = TimeZoneUtil.getServerDate1(paramValue, "begin");
            //							if(!paramValue.equals(time_paramValue)){
            //								time_paramValue = paramValue;
            //							}
            if ("doclastmoddate".equals(condition.getName())
                || "doccreatedate".equals(condition.getName())) {
              String doclastmodtime = TimeZoneUtil.getServertime1(paramValue, "begin");
              sqlWhere +=
                  TimeZoneUtil.handDateCondition(
                      "6", paramValue, "", condition.getName(), "", false);
            } else {
              sqlWhere +=
                  " and "
                      + condition.getName()
                      + ">='"
                      + time_paramValue
                      + "'"; // + " and " + condition.getName() + "=" + paramValue;
            }

            //						}
          } else if (paramName.equals(condition.getName() + ConditionUtil.DATE_TO)) {
            //						if(!paramValue.equals(request.getParameter(condition.getName() +
            // ConditionUtil.DATE_FROM))){ //开始日期!=结束日期
            //							paramValue = TimeZoneUtil.getServerDate1(paramValue,"end");
            String time_paramValue = TimeZoneUtil.getServerDate1(paramValue, "end");
            //							if(!paramValue.equals(time_paramValue)){
            //								time_paramValue = paramValue;
            //							}
            if ("doclastmoddate".equals(condition.getName())
                || "doccreatedate".equals(condition.getName())) {
              String doclastmodtime = TimeZoneUtil.getServertime1(paramValue, "end");
              sqlWhere +=
                  TimeZoneUtil.handDateCondition(
                      "6", "", paramValue, condition.getName(), "", false);
              //								sqlWhere += " and (" + condition.getName() + "<='" +  time_paramValue + "'"
              // + " and " + "doclastmodtime<='"+ doclastmodtime +"')";
            } else {
              sqlWhere +=
                  " and "
                      + condition.getName()
                      + "<='"
                      + time_paramValue
                      + "'"; // + " and " + condition.getName() + "=" + paramValue;
            }
            //							sqlWhere += " and " + condition.getName() + "<='" +  time_paramValue + "'";
            //						}
          }
          continue;
        }

        if (condition.getConditionType() == ConditionType.SCOPE) {
          if (paramName.equals(DocCondition.REPLAY_DOC_COUNT + ConditionUtil.INTERVAL_FROM)) {
            String _val = Util.getIntValue(paramValue, 0) + "";
            if (condition.getDbType() != DbType.INT) {
              _val = "'" + _val.replace("'", "'") + "'";
            }
            sqlWhere += " and " + condition.getName() + " >= " + _val;
          } else if (paramName.equals(DocCondition.REPLAY_DOC_COUNT + ConditionUtil.INTERVAL_TO)) {
            String _val = Util.getIntValue(paramValue, 0) + "";
            if (condition.getDbType() != DbType.INT) {
              _val = "'" + _val.replace("'", "'") + "'";
            }
            sqlWhere += " and " + condition.getName() + " <= " + _val;
          }
        }

        if (condition.getName().equals(paramName)) {
          isCustom = false;
          if (condition.getLogic() == LogicOperation.CUSTOM) {
            if (paramName.equals(DocCondition.DOC_SUBJECT.getName())) { // 标题
              sqlWhere += " and " + getDocSubjectSql(paramValue);
            } else if (paramName.equals(DocCondition.KEYWORD.getName())) { // 关键字
              sqlWhere += " and " + getKeyWordSql(paramValue);
            } else if (paramName.equals(DocCondition.DEPARTMENT_ID.getName())) { // 创建部门
              sqlWhere +=
                  " and exists(select 1 from HrmResource where departmentid="
                      + paramValue
                      + " and id=t1.doccreaterid)";
            } else if (paramName.equals(DocCondition.CREATER_SUBCOMPANY_ID.getName())) { // 创建人分部
              sqlWhere +=
                  " and exists(select 1 from HrmResource where subcompanyid1="
                      + paramValue
                      + " and id=t1.doccreaterid)";
            } else if (paramName.equals(DocCondition.OWNER_DEPARTMENT_ID.getName())) { // 所有者部门
              sqlWhere +=
                  " and exists(select 1 from HrmResource where departmentid="
                      + paramValue
                      + " and id=t1.ownerid)";
            } else if (paramName.equals(DocCondition.OWNER_SUBCOMPANY_ID.getName())) { // 所有者分部
              sqlWhere +=
                  " and exists(select 1 from HrmResource where subcompanyid1="
                      + paramValue
                      + " and id=t1.ownerid)";
            } else if (paramName.equals(DocCondition.DATE2DURING.getName())) { // 修改期间
              if (Util.getIntValue(paramValue, 0) > 36
                  || Util.getIntValue(paramValue, 0) < 1) { // 表示全部
                continue;
              }
              sqlWhere +=
                  " and t1.doclastmoddate>='"
                      + getDate2During(Util.getIntValue(paramValue, 0))
                      + "'";
            } else if (paramName.equals(DocCondition.DOC_STATUS.getName())) { // 文档状态
              docstatus = paramValue;
            } else if (paramName.equals(DocCondition.TREE_DOC_FIELD_ID.getName())) { // 虚拟目录
              paramValue = paramValue.startsWith(",") ? paramValue.substring(1) : paramValue;
              paramValue =
                  paramValue.endsWith(",")
                      ? paramValue.substring(0, paramValue.length() - 1)
                      : paramValue;

              paramValue =
                  paramValue.indexOf(",") == -1
                      ? (" = " + paramValue)
                      : (" in (" + paramValue + ")");

              sqlWhere +=
                  " and exists(select 1 from DocDummyDetail where docid=t1.id and catelogid "
                      + paramValue
                      + ")";
            }

          } else if (condition.getLogic() == LogicOperation.EQ_OR_IN) {
            paramValue = paramValue.startsWith(",") ? paramValue.substring(1) : paramValue;
            paramValue =
                paramValue.endsWith(",")
                    ? paramValue.substring(0, paramValue.length() - 1)
                    : paramValue;
            // 分为文档订阅部分的高级搜索条件拼接
            if (paramValue.indexOf(",") == -1) {
              if (condition.getDbType() == DbType.VARCHAR)
                paramValue = "'" + paramValue.replace("'", "''") + "'";
              paramValue = " = " + paramValue;
            } else {
              if (condition.getDbType() == DbType.VARCHAR)
                paramValue = "'" + paramValue.replace("'", "''").replace(",", "','") + "'";
              paramValue = " in (" + paramValue + ")";
            }

            if (condition == DocCondition.SUBSCRIPTION_APPROVE_DATE
                || condition == DocCondition.SUBSCRIPTION_DATE
                || condition == DocCondition.SUBSCRIPTION_STATE) {
              sqlWhere += " and ds." + paramName + paramValue;
            } else {

              sqlWhere += " and t1." + paramName + paramValue;
            }

          } else if (condition.getLogic() != null) { // 分为文档订阅部分的高级搜索条件拼接
            String _code = condition.getLogic().getCode();
            if (_code == null) continue;

            if (condition.getDbType() == DbType.VARCHAR) {
              if (_code.indexOf("{#}") > -1) {
                paramValue = paramValue.replace("'", "''");
              } else {
                paramValue = "'" + paramValue.replace("'", "''") + "'";
              }
            }
            if (condition == DocCondition.SUBSCRIPTION_APPROVE_DATE
                || condition == DocCondition.SUBSCRIPTION_DATE
                || condition == DocCondition.SUBSCRIPTION_STATE) {
              sqlWhere +=
                  " and ds."
                      + paramName
                      + (_code.indexOf("{#}") > -1
                          ? _code.replace("{#}", paramValue)
                          : (_code + paramValue));
            } else {
              sqlWhere +=
                  " and t1."
                      + paramName
                      + (_code.indexOf("{#}") > -1
                          ? _code.replace("{#}", paramValue)
                          : (_code + paramValue));
            }
          }
          break;
        }
      }

      // 处理自定义字段
      // 如果开启了自定义查询，当前的条件是自定义字段中的值，则进行检查
      if (isCustom
          && ConditionUtil.isCustomParamNameNew(paramName)
          && ConditionUtil.isCustomParamValue(paramName)) {
        String id = ConditionUtil.getCustomIdNew(paramName);

        int secid = Util.getIntValue(Util.null2String(request.getParameter("seccategory")));
        if (docTableType == DocTableType.DOC_COPYMOVE) {
          sqlWhere = " t1.seccategory = " + request.getParameter("sourceId");
        }

        String fieldValue = paramValue;
        String fieldOpt =
            Util.null2String(
                request.getParameter(
                    ConditionUtil.CUSTOM_KEY_PREV + id + ConditionUtil.CUSTOM_KEY_OPT),
                "-1");

        String customSqlWhere = ConditionUtil.getCustomSql(id, secid, user, fieldValue, fieldOpt);
        if (!customSqlWhere.isEmpty()) {
          customSql += " and " + customSqlWhere;
        }
      }
    }

    String eqOrInBelongtoidsForSql =
        needRight
            ? (belongtoids.isEmpty() ? (" = " + user.getUID()) : (" in (" + belongtoids + ")"))
            : "";

    // 处理特殊字段
    docstatus = docstatus.startsWith(",") ? docstatus.substring(1) : docstatus;
    docstatus =
        docstatus.endsWith(",") ? docstatus.substring(0, docstatus.length() - 1) : docstatus;
    if (docTableType == DocTableType.MY_DOC_TABLE) { // 我的文档
      if (docstatus.isEmpty()) {
        sqlWhere += " and t1.docstatus != 8 and t1.docstatus != 9 and t1.docstatus <=9";
      } else {
        sqlWhere +=
            " and t1.docstatus "
                + (docstatus.indexOf(",") > -1 ? ("in (" + docstatus + ")") : ("=" + docstatus));
      }

      sqlWhere +=
          " and (t1.doccreaterid "
              + eqOrInBelongtoidsForSql
              + " or t1.ownerid "
              + eqOrInBelongtoidsForSql
              + ")";
    } else if (docTableType == DocTableType.DOC_BATCHSHARE) { // 批量共享
      if (needRight) {
        // sqlWhere += " and (t1.docstatus in(1,2,5) or (t1.docstatus=7  and (sharelevel>1 or
        // (t1.doccreaterid="+user.getUID()+" or t1.ownerid="+user.getUID()+"))))";
        sqlWhere +=
            " and (t1.docstatus in(1,2,5) or (t1.docstatus=7  and (t1.doccreaterid="
                + user.getUID()
                + " or t1.ownerid="
                + user.getUID()
                + ")))";
      } else {
        sqlWhere += " and t1.docstatus in(1,2,5,7) ";
      }
    } else if (docTableType == DocTableType.DOC_COPYMOVE
        || docTableType == DocTableType.ENGINE_DOC_BATCHSHARE) { // 复制、移动   后台批量调整共享
      if (docstatus.isEmpty()) {
        sqlWhere += " and t1.docstatus in(1,2,5,7)";
      } else {
        docstatus = docstatus.equals("1") ? "1,2" : docstatus; // 页面查询条件1表示 同时查询 正常、生效两种状态
        sqlWhere +=
            " and t1.docstatus "
                + (docstatus.indexOf(",") > -1 ? ("in (" + docstatus + ")") : ("=" + docstatus));
      }
    } else if (docTableType == DocTableType.DOC_RECYCLE) { // 文档回收站
      if (!docstatus.isEmpty()) {
        docstatus = docstatus.equals("1") ? "1,2" : docstatus; // 页面查询条件1表示 同时查询 正常、生效两种状态
        sqlWhere +=
            " and t1.docstatus "
                + (docstatus.indexOf(",") > -1 ? ("in (" + docstatus + ")") : ("=" + docstatus));
      }
    } else if (docTableType == DocTableType.ENGINE_DOC_RECYCLE) { // 文档回收(后台)
      if (!docstatus.isEmpty()) {
        docstatus = docstatus.equals("1") ? "1,2" : docstatus; // 页面查询条件1表示 同时查询 正常、生效两种状态
        sqlWhere +=
            " and t1.docstatus "
                + (docstatus.indexOf(",") > -1 ? ("in (" + docstatus + ")") : ("=" + docstatus));
      }
    } else if (docTableType == DocTableType.DOC_SUBSCRIPTION_HISTORY) { // 文档订阅历史
      if (docstatus.isEmpty()) {
        //	sqlWhere += " and t1.docstatus in(1,2,5) ";
        if (needRight) {
          // sqlWhere += " and (t1.docstatus in(1,2,5) or (t1.docstatus=7  and (sharelevel>1 or
          // (t1.doccreaterid="+user.getUID()+" or t1.ownerid="+user.getUID()+"))))";
          // ayh 默认可以查看全部文档，包括非正常状态的文档

          /*          sqlWhere +=
          " and (t1.docstatus in(1,2,5) or (t1.docstatus=7  and (t1.doccreaterid="
              + user.getUID()
              + " or t1.ownerid="
              + user.getUID()
              + ")))";*/
          sqlWhere +=
              " and (t1.docstatus in(1,2,3,4,5,6,7,8,9) or (t1.docstatus=7  and (t1.doccreaterid="
                  + user.getUID()
                  + " or t1.ownerid="
                  + user.getUID()
                  + ")))";
        } else {
//          ayh 默认可以参看全部文档，包括处于非正常状态的文档
//          sqlWhere += " and t1.docstatus in(1,2,5) ";
            sqlWhere += " and t1.docstatus in(1,2,3,4,5,6,7,8,9) ";
        }
      } else {
        docstatus = docstatus.equals("1") ? "1,2" : docstatus; // 页面查询条件1表示 同时查询 正常、生效两种状态
        sqlWhere +=
            " and t1.docstatus "
                + (docstatus.indexOf(",") > -1 ? ("in (" + docstatus + ")") : ("=" + docstatus));
      }

      if (docTableType == DocTableType.NEWEST_DOC
          || docTableType == DocTableType.NO_READ_DOC) { // 最新文档（未读文档）
        sqlWhere +=
            " and t1.doccreaterid "
                + (belongtoids.isEmpty()
                    ? ("<> " + user.getUID())
                    : ("not in (" + belongtoids + ")"));
      }
    } else if (docTableType == DocTableType.ENGINE_DOC_PROP_SET) { // 文档弹出窗口设置
      sqlWhere += " and t1.docstatus in(1,2,5) and t1.docextendname = 'html'";
    } else {
      if (docstatus.isEmpty()) {
        //	sqlWhere += " and t1.docstatus in(1,2,5) ";
        if (needRight) {
          // sqlWhere += " and (t1.docstatus in(1,2,5) or (t1.docstatus=7  and (sharelevel>1 or
          // (t1.doccreaterid="+user.getUID()+" or t1.ownerid="+user.getUID()+"))))";
//          ayh
//          sqlWhere +=
//              " and (t1.docstatus in(1,2,5) or (t1.docstatus=7  and (t1.doccreaterid="
//                  + user.getUID()
//                  + " or t1.ownerid="
//                  + user.getUID()
//                  + ")))";
          sqlWhere +=
                  " and (t1.docstatus in(1,2,3,4,5,6,7,8,9) or (t1.docstatus=7  and (t1.doccreaterid="
                          + user.getUID()
                          + " or t1.ownerid="
                          + user.getUID()
                          + ")))";
        } else {
//          ayh
//          sqlWhere += " and t1.docstatus in(1,2,5) ";
          sqlWhere += " and t1.docstatus in(1,2,3,4,5,6,7,8,9) ";
        }
      } else {
        docstatus = docstatus.equals("1") ? "1,2" : docstatus; // 页面查询条件1表示 同时查询 正常、生效两种状态
        sqlWhere +=
            " and t1.docstatus "
                + (docstatus.indexOf(",") > -1 ? ("in (" + docstatus + ")") : ("=" + docstatus));
      }

      if (docTableType == DocTableType.NEWEST_DOC
          || docTableType == DocTableType.NO_READ_DOC) { // 最新文档（未读文档）
        sqlWhere +=
            " and t1.doccreaterid "
                + (belongtoids.isEmpty()
                    ? ("<> " + user.getUID())
                    : ("not in (" + belongtoids + ")"));
      }
    }

    String isNew = Util.null2String(request.getParameter("isNew"));
    if ("yes".equals(isNew)
        || docTableType == DocTableType.NEWEST_DOC
        || docTableType == DocTableType.NO_READ_DOC) {
      sqlWhere +=
          " and not exists(select 1 from docReadTag where t1.id=docid and userid "
              + eqOrInBelongtoidsForSql
              + " and usertype=1)";
    }

    if (!customSql.isEmpty()) {
      sqlWhere +=
          " and exists(select 1 from cus_fielddata tcm where scope='"
              + ConditionUtil.CUSTOM_SCOPE
              + "' and id=t1.id "
              + customSql
              + ")";
    }

    if (docTableType == DocTableType.DOC_BATCHSHARE && needRight) { // 批量共享(不需要权限的是后台批量共享)
      // sqlWhere += " and sharelevel=3 and exists(select 1 from DocSecCategory where
      // DocSecCategory.id=t1.secCategory and DocSecCategory.shareable='1')";
      sqlWhere +=
          " and exists(select 1 from DocSecCategory where DocSecCategory.id=t1.secCategory and DocSecCategory.shareable='1')";
    }

    // if(needRight){
    if (docTableType == DocTableType.DOC_OUT_TABLE) { // 登录前门户more(只取内部)
      boolean secretFlag = CheckPermission.isOpenSecret();
      if (secretFlag) sqlWhere += " and t1.secretLevel=" + DocManager.DEFAILT_SECRET_LEVEL;
    } else {
      sqlWhere += DocListUtil.getSecretSql(user, " and t1.secretLevel");
    }
    // }

    // 统一过滤字段
    if (docTableType != DocTableType.DOC_SUBSCRIPTION_HISTORY
        && docTableType != DocTableType.DOC_SUBSCRIPTION_APPROVE
        && docTableType != DocTableType.DOC_SUBSCRIPTION_BACK
        && docTableType != DocTableType.DOC_RECYCLE) { // 非文档订阅过虑历史文件 、 非回收站
      sqlWhere += " and (t1.ishistory is null or t1.ishistory = 0)";
    }

    if (docTableType == DocTableType.DOC_RECYCLE) { // 文档回收站
      sqlWhere += " and t1.ishistory != 1 ";
      sqlWhere += " and t1.docdeleteuserid=" + user.getUID();
    } else if (docTableType == DocTableType.ENGINE_DOC_RECYCLE) { // 文档回收站(后台)
      sqlWhere += " and t1.ishistory != 1 ";
    } else {
      sqlWhere += " and (t1.isreply is null or t1.isreply='' or t1.isreply='0')";
    }

    sqlWhere = sqlWhere.trim().startsWith("and") ? sqlWhere.substring(4) : sqlWhere;

    // 初次进入列表，代入默认值条件
    packDefaultValue(request, user, docTableType);
  }

  public static String getSecretSql(User user, String column) {
    boolean secretFlag = CheckPermission.isOpenSecret();
    if (secretFlag) {
      HrmClassifiedProtectionBiz hcpb = new HrmClassifiedProtectionBiz();
      String userSecretLevel = user == null ? "" : hcpb.getMaxResourceSecLevel(user);
      return column + ">=" + Util.getIntValue(userSecretLevel, DocManager.DEFAILT_SECRET_LEVEL); //
    }
    return "";
  }

  public static Map<String, String> getCreateDate(HttpServletRequest request) {
    String select =
        request.getParameter(DocCondition.DOC_CREATEDATE_SELECT + ConditionUtil.DATE_SELECT);
    String from =
        request.getParameter(DocCondition.DOC_CREATEDATE_SELECT + ConditionUtil.DATE_FROM);
    String to = request.getParameter(DocCondition.DOC_CREATEDATE_SELECT + ConditionUtil.DATE_TO);

    Map<String, String> dateMap = new HashMap<String, String>();
    if ("0".equals(select)) {
      return dateMap;
    }
    dateMap = packDate(select, from, to);

    from = dateMap.get("from");
    to = dateMap.get("to");

    if (from != null && !from.isEmpty()) {
      from = new TimeZoneUtil().getServerDate(from + " 00:00:00");
    }
    if (to != null && !to.isEmpty()) {
      to = new TimeZoneUtil().getServerDate(to + " 23:59:59");
    }

    dateMap.put(DocCondition.DOC_CREATEDATE_SELECT.getName() + ConditionUtil.DATE_FROM, from);
    dateMap.put(DocCondition.DOC_CREATEDATE_SELECT.getName() + ConditionUtil.DATE_TO, to);

    return dateMap;
  }

  /**
   * 初始进入列表，代入默认值条件
   *
   * @author wangqs
   */
  public void packDefaultValue(HttpServletRequest request, User user, DocTableType docTableType) {

    //
    /***
     * String during = request.getParameter(DocCondition.DATE2DURING.getName());
     * if(during == null){
     * List<SearchConditionOption> options = ConditionUtil.getDateSelectDuring(user.getLanguage());
     * int date = 0;
     * for(SearchConditionOption option : options){
     * if(option.isSelected()){
     * date = Util.getIntValue(option.getKey(),0);
     * }
     * }
     * if(date >= 1 && date <= 36){
     *
     * sqlWhere += " and t1.doclastmoddate>='" + getDate2During(date) + "'";
     * }
     * }
     *
     ***/

    // 最新文档有tab页，未读文档没有tab页
    if (docTableType == DocTableType.NEWEST_DOC) { // 最新文档
      try {
        sqlWhere += this.packSearchTabDate(request.getParameter(ConditionUtil.TAB_REQ_NAME));
      } catch (Exception e) {
        e.printStackTrace();
      }
    } else if (docTableType == DocTableType.MY_DOC_TABLE
        || docTableType == DocTableType.SEARCH_DOC_TABLE
        || docTableType == DocTableType.CATEGORY_DOC_TABLE) { // 我的文档、查询文档、文档目录
      try {
        // 0-全部，1-今天，2-本周，3-本月，4-本季，5-本年

        int tab =
            Util.getIntValue(
                request.getParameter(ConditionUtil.TAB_REQ_NAME), ConditionUtil.TAB_DATE_DEFAULT);

        String updateDate =
            Util.null2String(
                request.getParameter(
                    DocCondition.DOC_LAST_MODDATE.getName() + ConditionUtil.DATE_SELECT));

        if (updateDate.isEmpty()) { // 没有修改日期，取默认时间
          //	sqlWhere += packDateType(DocCondition.DOC_LAST_MODDATE.getName(),tab + "");
        }

      } catch (Exception e) {
        e.printStackTrace();
      }
    }

    sqlWhere = sqlWhere.trim().startsWith("and") ? sqlWhere.substring(4) : sqlWhere;
  }

  /** 处理修改期间(最近n月)条件的查询 */
  public static String getDate2During(int month) {
    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.DATE, -30 * month);
    Date cDate = new Date(calendar.getTimeInMillis());
    return new SimpleDateFormat("yyyy-MM-dd").format(cDate);
  }

  /** 处理特殊时间类型(今天、本周、本月....)条件查询 0-全部，1-今天，2-本周，3-本月，7-上个月，4-本季，5-本年，8-上一年，6-指定日期范围 */
  public static String packDateType(String column, String value, DocCondition condition) {
    Map<String, String> dateMap = packDate(value, "", "");
    String sdate = Util.null2String(dateMap.get("from"));
    String edate = Util.null2String(dateMap.get("to"));

    if ("0".equals(value)) {
      return "";
    }

    if (condition == DocCondition.SUBSCRIPTION_APPROVE_DATE
        || condition == DocCondition.SUBSCRIPTION_DATE
        || condition == DocCondition.SUBSCRIPTION_STATE) {
      if (!sdate.isEmpty()) {
        if ("8".equals(value)) {
          return TimeZoneUtil.handDateCondition(value, sdate, edate, column, "ds", false, true);
        } else {
          return TimeZoneUtil.handDateCondition(value, sdate, edate, column, "ds", false, true);
        }
        //				if(sdate.equals(edate)){
        ////					return TimeZoneUtil.handDateCondition(value,sdate,"",column,"ds",false,true);
        //					return " and ds." + column + "='" + sdate + "'";
        //				}else{
        ////					return TimeZoneUtil.handDateCondition(value,sdate,"",column,"ds",false,true);
        //					String test = " and ds." + column + ">='" + sdate + "' and ds." + column + "<='" +
        // edate + "'";
        //					return test;
        //				}
      }
    } else {
      if (!sdate.isEmpty()) {
        if ("8".equals(value)) {
          return TimeZoneUtil.handDateCondition(value, sdate, edate, column, "t1", false, true);
        } else {
          return TimeZoneUtil.handDateCondition(value, sdate, edate, column, "t1", false, true);
        }
        //				if(sdate.equals(edate)){
        //					return " and t1." + column + "='" + sdate + "'";
        //				}else{
        //					String test = " and t1." + column + ">='" + sdate + "' and t1." + column + "<='" +
        // edate + "'";
        //					return test;
        //				}
      }
    }

    return "";
  }

  /**
   * 处理特殊时间类型(今天、本周、本月....)条件查询 0-全部，1-今天，2-本周，3-本月，7-上个月，4-本季，5-本年，8-上一年，6-指定日期范围
   *
   * @author wangqs
   * @params select-类型值，from-指定类型的开始日期，to-指定日期的结束日期
   */
  public static Map<String, String> packDate(String select, String from, String to) {
    Map<String, String> dateMap = new HashMap<String, String>();

    String sdate = "";
    String edate = TimeUtil.getCurrentDateString();
    switch (Util.getIntValue(select, 0)) {
      case 1:
        sdate = TimeUtil.getCurrentDateString();
        break;
      case 2:
        sdate = TimeUtil.getFirstDayOfWeek();
        break;
      case 3:
        sdate = TimeUtil.getFirstDayOfMonth();
        break;
      case 4:
        sdate = TimeUtil.getFirstDayOfSeason();
        break;
      case 5:
        sdate = TimeUtil.getFirstDayOfTheYear();
        break;
      case 6:
        sdate = from;
        edate = to;
      case 7:
        sdate = TimeUtil.getLastMonthBeginDay();
        edate = TimeUtil.getLastMonthEndDay();
        break;
      case 8:
        sdate = TimeUtil.getFirstDayOfLastYear();
        edate = TimeUtil.getEndDayOfLastYear();
        break;
      default:
        break;
    }

    //		TimeZoneUtil timeZoneUtil = new TimeZoneUtil();
    //		//多时区转换
    //		sdate = timeZoneUtil.getServerDate(sdate,"begin");
    //		edate = timeZoneUtil.getServerDate(edate,"end");

    dateMap.put("from", sdate);
    dateMap.put("to", edate);

    return dateMap;
  }

  /** 根据规则 处理有主题条件的查询 */
  private String getDocSubjectSql(String docsubject) {
    String tmpString = "";
    docsubject = docsubject.replaceAll("'", "''").replaceAll("\"", "&quot;");
    if ((docsubject.indexOf(" ") == -1 && docsubject.indexOf("+") == -1)
        || (docsubject.indexOf(" ") != -1 && docsubject.indexOf("+") != -1)) {
      tmpString += " t1.docsubject like '%" + docsubject + "%'";
    } else if (docsubject.indexOf(" ") != -1 && docsubject.indexOf("+") == -1) {
      String orArray[] = Util.TokenizerString2(docsubject, " ");
      if (orArray.length > 0) {
        tmpString += "  ( ";
      }
      for (int i = 0; i < orArray.length; i++) {
        tmpString += " t1.docsubject like '%" + orArray[i] + "%'";
        if (i + 1 < orArray.length) {
          tmpString += " or ";
        }
      }
      if (orArray.length > 0) {
        tmpString += " ) ";
      }
    } else if (docsubject.indexOf(" ") == -1 && docsubject.indexOf("+") != -1) {
      String andArray[] = Util.TokenizerString2(docsubject, "+");
      for (int i = 0; i < andArray.length; i++) {
        tmpString += " t1.docsubject like '%" + andArray[i] + "%'";
        if (i + 1 < andArray.length) {
          tmpString += " and ";
        }
      }
    }
    return tmpString;
  }

  /** 根据规则 处理有关键字条件的查询 */
  private String getKeyWordSql(String keyword) {
    String keywordSql = "";
    keyword = keyword.trim().replaceAll("'", "''");
    ArrayList keywordList = Util.TokenizerString(keyword, " ");
    if (keywordList != null && keywordList.size() > 0) {
      for (int i = 0; i < keywordList.size(); i++) {
        String tempkeyword = (String) keywordList.get(i);
        keywordSql +=
            keywordSql.equals("")
                ? " t1.keyword like '%" + tempkeyword + "%' "
                : " or t1.keyword like '%" + tempkeyword + "%' ";
      }
      if (!keywordSql.equals("")) {
        keywordSql = " (" + keywordSql + ") ";
      }
    }
    return keywordSql;
  }

  /**
   * 最新文档tab页转换成 sql条件
   *
   * @author wangqs
   */
  private String packSearchTabDate(String tabValue) throws Exception {
    String sql = "";

    switch (Util.getIntValue(tabValue, ConditionUtil.TAB_DEFAULT_VALUE)) {
      case ConditionUtil.TAB_TODAY_VALUE:
        sql = " and t1.doccreatedate='" + TimeUtil.getCurrentDateString() + "'";
        break;
      case ConditionUtil.TAB_WEEK_VALUE:
        sql = " and t1.doccreatedate>='" + TimeUtil.getFirstDayOfWeek() + "'";
        sql += " and t1.doccreatedate<='" + TimeUtil.getLastDayOfWeek() + "'";
        break;
      case ConditionUtil.TAB_MONTH_VALUE:
        sql = " and t1.doccreatedate>='" + TimeUtil.getFirstDayOfMonth() + "'";
        sql += " and t1.doccreatedate<='" + TimeUtil.getLastDayOfMonth() + "'";
        break;
      case ConditionUtil.TAB_SESSION_VALUE:
        sql = " and t1.doccreatedate>='" + TimeUtil.getFirstDayOfSeason() + "'";
        sql += " and t1.doccreatedate<='" + TimeUtil.getLastDayDayOfSeason() + "'";
        break;
      case ConditionUtil.TAB_YEAR_VALUE:
        sql = " and t1.doccreatedate>='" + TimeUtil.getFirstDayOfTheYear() + "'";
        sql += " and t1.doccreatedate<='" + TimeUtil.getLastDayOfYear() + "'";
        break;
      default:
        break;
    }

    return sql;
  }

  public String getSqlWhere() {
//    ayh
    new BaseBean().writeLog("create sql string from docListUtil, sqlWhere is :" + this.sqlWhere);
    return this.sqlWhere;
  }
}
